package com.bjy.qa.service.functionaltest.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjy.qa.dao.functionaltest.ApiHistoryDao;
import com.bjy.qa.entity.functionaltest.*;
import com.bjy.qa.service.functionaltest.IApiHistoryService;
import com.bjy.qa.service.functionaltest.IApiParamHistoryService;
import com.bjy.qa.util.security.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ApiHistoryService extends ServiceImpl<ApiHistoryDao, ApiHistory> implements IApiHistoryService {

    @Resource
    ApiHistoryDao apiHistoryDao;

    @Resource
    IApiParamHistoryService iApiParamHistoryService;

    @Override
    public ApiHistory add(Api api, String userName) {
        ApiHistory apiHistory = JSON.parseObject(JSON.toJSONString(api), ApiHistory.class);
        apiHistory.setApiId(api.getId());
        apiHistory.setHistoryDesigner(userName);
        apiHistory.setUpdatedAt(null);
        apiHistory.setCreatedAt(null);
        apiHistory.setId(null);
        apiHistoryDao.insert(apiHistory);

        List<ApiParamHistory> apiParamHistories = JSON.parseArray(JSON.toJSONString(api.getApiParams()), ApiParamHistory.class);
        if (apiParamHistories != null){
            for (ApiParamHistory apiParamHistory : apiParamHistories) {
                apiParamHistory.setApiHistoryId(apiHistory.getId());
                apiParamHistory.setApiParamId(apiParamHistory.getId());
                apiParamHistory.setId(null);
                apiParamHistory.setUpdatedAt(null);
                apiParamHistory.setCreatedAt(null);
            }
            iApiParamHistoryService.saveBatch(apiParamHistories);
        }

        apiHistory.setApiParamHistories(apiParamHistories);

        return apiHistory;
    }

    @Override
    public List<ApiHistory> selectByApiId(Long projectId, Long apiId) {
        return apiHistoryDao.selectByApiId(projectId, apiId);
    }
}
